import socket
import optparse
def port_scan(ip, port):#socket 去连接看返回值
    try:
        s= socket.socket()
#设置一个连接超时的时间
        s.settimeout(5)
        if s.connect_ex((ip,port))== 0:#connect ex()在连接失败时不会抛出异常，而是返回一个错误码。如果连接成功，则返回 0(即没有错误)。
            print('[+]Host:{},Port{}, status:OPEN'.format(ip, port))
        else:
            print('[+] Host:{}, Port{},status:CLosE'.format(ip, port))
    except Exception as e:
        print(e)
        pass
    finally:
        s.close()
def main():

    parser = optparse.OptionParser('<Usage >')
    parser.add_option('-i', dest='ip', type='string', help='target ip')
    parser.add_option('-p','--port', dest='port', type='string', help='target port,可以用单个端口，也可以用一个端口范围，比如8000-9000')
    opts,args = parser.parse_args()
    ip = opts.ip
    port = opts.port
    if ip is None or port is None:
        print('请输入 -h 查看命令手册1')
        return
    try :
        if'-'in port:
            start_port,end_port = port.split('-')
            for p in range(int(start_port),int(end_port)+ 1):
                port_scan(ip,p)
        else:
            port_scan(ip,int(port))
    except Exception as e:
        print('请输入 -h 查看命令手册')
        print(e)
if __name__== '__main__':
    main()